﻿using Core.FrameWork.Commons.Http.Abstraction;
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

namespace Core.Polly.Web
{
    public class HttpClientFactory : IHttpClient
    {
        private readonly IHttpClientFactory _httpClientFactory;

        public HttpClientFactory(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        /// <summary>
        /// Get请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="serviceName"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public async Task<T> GetAsync<T>(string serviceName, string url)
        {
            try
            {
                System.Net.Http.HttpClient httpClient = _httpClientFactory.CreateClient(serviceName);

                HttpResponseMessage response = await httpClient.GetAsync(url);

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    throw new Exception($"Http请求调用错误，异常{await response.Content.ReadAsStringAsync()}，错误码:{response.StatusCode}。");
                }

                var content = await response.Content.ReadAsStringAsync();

                return JsonSerializer.Deserialize<T>(content);
            }
            catch (Exception ex)
            {
                throw new Exception($"异常错误：{ex.Message.ToString()}");

            }

        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="httpContent"></param>
        /// <returns></returns>
        public async Task<T> PostAsync<T>(string url, HttpContent httpContent)
        {
            try
            {
                System.Net.Http.HttpClient httpClient = _httpClientFactory.CreateClient();

                HttpResponseMessage response = await httpClient.PostAsync(url, httpContent);

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    throw new Exception($"Http请求调用错误，异常{await response.Content.ReadAsStringAsync()}，错误码:{response.StatusCode}。");
                }

                var content = await response.Content.ReadAsStringAsync();

                return JsonSerializer.Deserialize<T>(content);
            }
            catch (Exception ex)
            {
                throw new Exception($"异常错误：{ex.ToString()}");
            }
        }
    }
}
